package com.ioffice.export.excel.template.tree;

import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.ioffice.exception.IOfficeException;
import com.ioffice.export.excel.sheet.ExcelSheet;
import com.ioffice.export.excel.sheet.cell.SheetCell;
import com.ioffice.export.excel.sheet.tree.ExcelSheetTree;
import com.ioffice.export.excel.template.AbstarctExportExcelTemplate;
import com.ioffice.export.excel.sheet.tree.SheetDataBody;

/**
 * 
 * @author <a href="mailto:goodluck.sunlight@gmail.com">chenboning</a>
 *
 * 
 * @descption 按照树形结构进行解析对象
 *
 * @version 1.0
 *
 *
 * @time  2013-5-21  下午1:28:20
 */
public class ExportExcelTreeTemplate extends AbstarctExportExcelTemplate{

	
	private Sheet sheet=null;
	private String defaultValue="--";
	private ExcelSheetTree sheetTree;
	
	public ExportExcelTreeTemplate() {
	}
	
	public ExportExcelTreeTemplate(String defaultValue) {
		this.defaultValue=defaultValue;
	}
	
	
	@Override
	public void writeOneExcel(Workbook wb, ExcelSheet excelSheet)throws IOException, IOfficeException {
		sheetTree=(ExcelSheetTree)excelSheet;
		sheet=wb.createSheet(sheetTree.getSheetName());
		super.setSheetCellByRowCountAndColCount(sheet, excelSheet.getRowCount(), excelSheet.getColCount(), defaultValue);
		//设置title
		setSheetGeneric(sheet, sheetTree.getSheetTitle());
		//设置交叉表头信息
		setSheetGeneric(sheet, sheetTree.getSheetCrossHeader());
		//设置上表头
		setSheetGeneric(sheet, sheetTree.getSheetTopHeader());
		//left header
		setSheetGeneric(sheet, sheetTree.getSheetLeftHeader());
		//databody
		setSheetDataBody(sheet, (SheetDataBody)sheetTree.getSheetDataBody());
		
		
		sheet=null;
	}

	private void setSheetDataBody(Sheet sheet, SheetDataBody dataBody){
		int x = dataBody.getX();
		int y = dataBody.getY();
		int xSpan = dataBody.getXspan();
		int ySpan = dataBody.getYspan();
		Row dataBodyRow;
		Cell dataBodyCell;
		SheetCell dataBodyCellModel;
		for(int rowIndex=y;rowIndex<y+ySpan;rowIndex++){
			dataBodyRow = sheet.getRow(rowIndex);
			for(int colIndex=x;colIndex<x+xSpan;colIndex++){
				dataBodyCellModel = dataBody.getSheetCell(rowIndex-y, colIndex-x);
				dataBodyCell = dataBodyRow.getCell(colIndex);
				dataBodyCell.setCellValue(dataBodyCellModel==null?"":dataBodyCellModel.getCellValue());
			}
		}
	}
}
